<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class HhmCategory extends Model
{
    use SoftDeletes;

    protected $table = 'ims_hhm_category';
    
    protected $fillable = [
        'uniacid', 'store_id', 'name', 'thumb', 'parent_id', 'description',
        'display_order', 'enabled', 'is_home', 'adv_img', 'adv_url', 'level',
        'advimg_pc', 'advurl_pc', 'plugin_id', 'filter_ids', 'small_adv_url'
    ];

    protected $casts = [
        'enabled' => 'boolean',
        'is_home' => 'boolean',
        'filter_ids' => 'json',
    ];

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const DELETED_AT = 'deleted_at';

    // 禁用时间戳自动转换为Carbon对象，因为表中使用整型存储
    public $timestamps = true;
    protected $dateFormat = 'U'; // 使用Unix时间戳

    /**
     * 关联父分类
     */
    public function parent()
    {
        return $this->belongsTo(HhmCategory::class, 'parent_id', 'id');
    }

    /**
     * 关联子分类
     */
    public function children()
    {
        return $this->hasMany(HhmCategory::class, 'parent_id', 'id')
            ->where('enabled', 1)
            ->orderBy('display_order', 'asc');
    }

    /**
     * 关联商品（多对多）
     */
    public function goods()
    {
        return $this->belongsToMany(
            HhmGoods::class,
            'ims_hhm_goods_category',
            'category_id',
            'goods_id'
        );
    }

    /**
     * 作用域：只查询启用的分类
     */
    public function scopeEnabled($query)
    {
        return $query->where('enabled', 1);
    }

    /**
     * 作用域：只查询一级分类
     */
    public function scopeFirstLevel($query)
    {
        return $query->where('parent_id', 0);
    }

    /**
     * 作用域：只查询二级分类
     */
    public function scopeSecondLevel($query)
    {
        return $query->where('parent_id', '>', 0);
    }

    /**
     * 获取缩略图完整URL
     */
    public function getThumbUrlAttribute()
    {
        if (empty($this->thumb)) {
            return '';
        }
        return \App\Services\ImageUrlService::processImageUrl($this->thumb);
    }

    /**
     * 获取广告图完整URL
     */
    public function getAdvImgUrlAttribute()
    {
        if (empty($this->adv_img)) {
            return '';
        }
        return \App\Services\ImageUrlService::processImageUrl($this->adv_img);
    }
}

